import requests
import warnings
import time
# 在 python 中字典重新赋值有坑：重新赋值会创建一个新字典，其他模块仍然引用原来的对象。
# 解决办法有：始终通过 config 模块访问；提供修改函数（推荐）；使用类封装（高级用法）；
from client import config

import logging
from middle.log import setup_logging
logger = logging.getLogger(__name__)

def deprecated(func):
    """这是一个自定义的废弃装饰器"""
    def wrapper(*args, **kwargs):
        warnings.warn(
            f"'{func.__name__}' is deprecated and will be removed in a future version.",
            DeprecationWarning,
            stacklevel=2
        )
        return func(*args, **kwargs)
    return wrapper

def base_get_request(url, params=None, headers=None, timeout=100):
    """
    封装GET请求
    :param url: 请求URL
    :param params: 查询参数字典
    :param headers: 请求头字典
    :param timeout: 超时时间(秒)
    :return: 响应内容(JSON格式)或None(请求失败时)
    """
    try:
        response = requests.get(
            url,
            params=params,
            headers=headers,
            timeout=timeout
        )
        logger.info(response)
        response.raise_for_status()  # 检查请求是否成功
        return response.json()  # 假设返回的是JSON数据
    except requests.exceptions.RequestException as e:
        logger.info(f"请求失败: {e}")
        return None

def base_post_request(url, json=None, headers=None, timeout=100):
    """
    封装一个 POST 请求的函数。

    Args:
        url (str): 目标 URL。
        json (array): 发送的请求数据，默认为 None。
        headers (dict, optional): 请求头，默认为 None。
        timeout (int, optional): 请求超时时间，默认为 10 秒。

    Returns:
        response (requests.Response): 返回的响应对象。
    """
    try:
        # 发送 POST 请求
        response = requests.post(url, json=json, headers=headers, timeout=timeout)

        # 判断请求是否成功
        response.raise_for_status()

        # 返回响应对象
        return response.json()

    except requests.exceptions.RequestException as e:
        # 如果请求发生异常，打印错误信息并返回 None
        logger.info(f"请求失败: {e}")
        return None

def get_10_v25Data():
    """
    获得 10 条 v25 的数据
    获得 1000 条 v25 的数据用 1.7 s ，效率还行，那就全部请求下来后，本地更新
    """
    response = base_get_request(
        config.BASE_GET_URL,
        params	= {"page": 1,
                   "limit": 10,
                   "os": "Server25",
                   "os_major_versions[]": "v25",
                   "os_minor_versions[]": "2500",
                   "source__icontains": "kernel",
                   "vul_upstream_status": "Fixed",
                   "status[]": "unprocessed"
                   },
        headers	= config.BASE_HEADERS,
    )
    items = response['data']
    return items

def test_status_get_10_v25Data():
    response = base_get_request(
        config.BASE_GET_URL,
        params	= {"page": 1,
                   "limit": 10,
                   "os": "Server25",
                   "os_major_versions[]": "v25",
                   "os_minor_versions[]": "2500",
                   "source__icontains": "kernel",
                   "vul_upstream_status": "Fixed",
                   "status[]": "unprocessed"
                   },
        headers	= config.BASE_HEADERS,
    )
    code = response['code']
    logger.info("code 值为：{}".format(code))
    if code == "20000":
        logger.info("是字符串 20000")
    elif code == 20000 :
        logger.info("是数字 20000")
    else:
        logger.info("值不对")

def get_1000_v25Data():
    """
    获得 10 条 v25 的数据
    获得 1000 条 v25 的数据用 1.7 s ，效率还行，那就全部请求下来后，本地更新
    """
    response = base_get_request(
        config.BASE_GET_URL,
        params	= {"page": 1,
                   "limit": 1000,
                   "os": "Server25",
                   "os_major_versions[]": "v25",
                   "os_minor_versions[]": "2500",
                   "source__icontains": "kernel",
                   "vul_upstream_status": "Fixed",
                   "status[]": "unprocessed"
                   },
        headers	= config.BASE_HEADERS,
    )
    items = response['data']
    return items

def get_all_v25_Data():
    """
    获得 1000 条 v20 的数据用 1.7 s ，效率还行，那就全部请求下来后，本地更新
    uos@guolongji:~/gh/vul_update$ pytest  tests/test_api.py -s |grep "Server25"|wc -l
    2025-07-04 16:32:37,334 - tests.test_api - INFO - GET请求耗时: 6.7828秒
    2724
    效率还行，那就全部前端来处理吧
    """
    page = 0
    all_items = []
    original_param = {"page": 1,
                      "limit": 1000,
                      "os": "Server25",
                      "os_major_versions[]": "v25",
                      "os_minor_versions[]": "2500",
                      "source__icontains": "kernel",
                      "vul_upstream_status": "Fixed",
                      "status[]": "unprocessed"
                      }
    while True:
        page = page + 1
        original_param["page"] = page
        response = base_get_request(
            config.BASE_GET_URL,
            params	= original_param,
            headers	= config.BASE_HEADERS,
        )
        piece_items = response['data']
        all_items = all_items + piece_items
        if len(piece_items) == 0:
            break
    return all_items

def get_all_v20_510e_1070_Data():
    """
    获取所有的 v20 510 1070 产线的数据。
    """
    page = 0
    all_items = []
    original_param = {"page": 1,
                      "limit": 1000,
                      "os": "ServerE",
                      "os_major_versions[]": "v20",
                      "os_minor_versions[]": "1070",
                      "source__icontains": "kernel-5.10",
                      "vul_upstream_status": "Fixed",
                      "status[]": "unprocessed"
                      }
    while True:
        page = page + 1
        original_param["page"] = page
        response = base_get_request(
            config.BASE_GET_URL,
            params	= original_param,
            headers	= config.BASE_HEADERS,
        )
        piece_items = response['data']
        all_items = all_items + piece_items
        if len(piece_items) == 0:
            break
    return all_items

def get_all_v20_510e_1060_Data():
    """
    获取所有的 v20 510 1060 产线的数据。
    """
    page = 0
    all_items = []
    original_param = {"page": 1,
                      "limit": 1000,
                      "os": "ServerE",
                      "os_major_versions[]": "v20",
                      "os_minor_versions[]": "1060",
                      "source__icontains": "kernel-5.10",
                      "vul_upstream_status": "Fixed",
                      "status[]": "unprocessed"
                      }
    while True:
        page = page + 1
        original_param["page"] = page
        response = base_get_request(
            config.BASE_GET_URL,
            params	= original_param,
            headers	= config.BASE_HEADERS,
        )
        piece_items = response['data']
        all_items = all_items + piece_items
        if len(piece_items) == 0:
            break
    return all_items

def get_all_v20_510e_1050_Data():
    """
    获取所有的 v20 510 1050 产线的数据。
    """
    page = 0
    all_items = []
    original_param = {"page": 1,
                      "limit": 1000,
                      "os": "ServerE",
                      "os_major_versions[]": "v20",
                      "os_minor_versions[]": "1050",
                      "source__icontains": "kernel-5.10",
                      "vul_upstream_status": "Fixed",
                      "status[]": "unprocessed"
                      }
    while True:
        page = page + 1
        original_param["page"] = page
        response = base_get_request(
            config.BASE_GET_URL,
            params	= original_param,
            headers	= config.BASE_HEADERS,
        )
        piece_items = response['data']
        all_items = all_items + piece_items
        if len(piece_items) == 0:
            break
    return all_items

def get_all_v20_510a_1070_Data():
    """
    获取所有的 v20 510 1070 产线的数据。
    """
    page = 0
    all_items = []
    original_param = {"page": 1,
                      "limit": 1000,
                      "os": "ServerA",
                      "os_major_versions[]": "v20",
                      "os_minor_versions[]": "1070",
                      "source__icontains": "kernel-5.10",
                      "vul_upstream_status": "Fixed",
                      "status[]": "unprocessed"
                      }
    while True:
        page = page + 1
        original_param["page"] = page
        response = base_get_request(
            config.BASE_GET_URL,
            params	= original_param,
            headers	= config.BASE_HEADERS,
        )
        piece_items = response['data']
        all_items = all_items + piece_items
        if len(piece_items) == 0:
            break
    return all_items

def get_all_v20_510a_1060_Data():
    """
    获取所有的 v20 510 1060 产线的数据。
    """
    page = 0
    all_items = []
    original_param = {"page": 1,
                      "limit": 1000,
                      "os": "ServerA",
                      "os_major_versions[]": "v20",
                      "os_minor_versions[]": "1060",
                      "source__icontains": "kernel-5.10",
                      "vul_upstream_status": "Fixed",
                      "status[]": "unprocessed"
                      }
    while True:
        page = page + 1
        original_param["page"] = page
        response = base_get_request(
            config.BASE_GET_URL,
            params	= original_param,
            headers	= config.BASE_HEADERS,
        )
        piece_items = response['data']
        all_items = all_items + piece_items
        if len(piece_items) == 0:
            break
    return all_items

def get_all_v20_510a_1050_Data():
    """
    获取所有的 v20 510 1050 产线的数据。
    """
    page = 0
    all_items = []
    original_param = {"page": 1,
                      "limit": 1000,
                      "os": "ServerA",
                      "os_major_versions[]": "v20",
                      "os_minor_versions[]": "1050",
                      "source__icontains": "kernel-5.10",
                      "vul_upstream_status": "Fixed",
                      "status[]": "unprocessed"
                      }
    while True:
        page = page + 1
        original_param["page"] = page
        response = base_get_request(
            config.BASE_GET_URL,
            params	= original_param,
            headers	= config.BASE_HEADERS,
        )
        if response == None:
            break
        piece_items = response['data']
        all_items = all_items + piece_items
        if len(piece_items) == 0:
            break
    return all_items

def get_all_v20_419A_1070_Data():
    """
    获取所有的 v20 419A 1070 产线的数据。
    """
    page = 0
    all_items = []
    original_param = {"page": 1,
                      "limit": 1000,
                      "os": "ServerA",
                      "os_major_versions[]": "v20",
                      "os_minor_versions[]": "1070",
                      "source__icontains": "kernel-4.19",
                      "vul_upstream_status": "Fixed",
                      "status[]": "unprocessed"
                      }
    while True:
        page = page + 1
        original_param["page"] = page
        response = base_get_request(
            config.BASE_GET_URL,
            params	= original_param,
            headers	= config.BASE_HEADERS,
        )
        piece_items = response['data']
        all_items = all_items + piece_items
        if len(piece_items) == 0:
            break
    return all_items

def get_all_v20_419A_1060_Data():
    """
    获取所有的 v20 419A 1060 产线的数据。
    """
    page = 0
    all_items = []
    original_param = {"page": 1,
                      "limit": 1000,
                      "os": "ServerA",
                      "os_major_versions[]": "v20",
                      "os_minor_versions[]": "1060",
                      "source__icontains": "kernel-4.19",
                      "vul_upstream_status": "Fixed",
                      "status[]": "unprocessed"
                      }
    while True:
        page = page + 1
        original_param["page"] = page
        response = base_get_request(
            config.BASE_GET_URL,
            params	= original_param,
            headers	= config.BASE_HEADERS,
        )
        piece_items = response['data']
        all_items = all_items + piece_items
        if len(piece_items) == 0:
            break
    return all_items

def get_all_v20_419A_1050_Data():
    """
    获取所有的 v20 419A 1050 产线的数据。
    """
    page = 0
    all_items = []
    original_param = {"page": 1,
                      "limit": 1000,
                      "os": "ServerA",
                      "os_major_versions[]": "v20",
                      "os_minor_versions[]": "1050",
                      "source__icontains": "kernel-4.19",
                      "vul_upstream_status": "Fixed",
                      "status[]": "unprocessed"
                      }
    while True:
        page = page + 1
        original_param["page"] = page
        response = base_get_request(
            config.BASE_GET_URL,
            params	= original_param,
            headers	= config.BASE_HEADERS,
        )
        if response == None:
            break
        piece_items = response['data']
        all_items = all_items + piece_items
        if len(piece_items) == 0:
            break
    return all_items

def get_all_v20_419E_1070_Data():
    """
    获取所有的 v20 419E 1070 产线的数据。
    """
    page = 0
    all_items = []
    original_param = {"page": 1,
                      "limit": 1000,
                      "os": "ServerE",
                      "os_major_versions[]": "v20",
                      "os_minor_versions[]": "1070",
                      "source__icontains": "kernel-4.19",
                      "vul_upstream_status": "Fixed",
                      "status[]": "unprocessed"
                      }
    while True:
        page = page + 1
        original_param["page"] = page
        response = base_get_request(
            config.BASE_GET_URL,
            params	= original_param,
            headers	= config.BASE_HEADERS,
        )
        piece_items = response['data']
        all_items = all_items + piece_items
        if len(piece_items) == 0:
            break
    return all_items

def get_all_v20_419E_1060_Data():
    """
    获取所有的 v20 419E 1060 产线的数据。
    """
    page = 0
    all_items = []
    original_param = {"page": 1,
                      "limit": 1000,
                      "os": "ServerE",
                      "os_major_versions[]": "v20",
                      "os_minor_versions[]": "1060",
                      "source__icontains": "kernel-4.19",
                      "vul_upstream_status": "Fixed",
                      "status[]": "unprocessed"
                      }
    while True:
        page = page + 1
        original_param["page"] = page
        response = base_get_request(
            config.BASE_GET_URL,
            params	= original_param,
            headers	= config.BASE_HEADERS,
        )
        piece_items = response['data']
        all_items = all_items + piece_items
        if len(piece_items) == 0:
            break
    return all_items

def get_all_v20_419E_1050_Data():
    """
    获取所有的 v20 419E 1050 产线的数据。
    """
    page = 0
    all_items = []
    original_param = {"page": 1,
                      "limit": 1000,
                      "os": "ServerE",
                      "os_major_versions[]": "v20",
                      "os_minor_versions[]": "1050",
                      "source__icontains": "kernel-4.19",
                      "vul_upstream_status": "Fixed",
                      "status[]": "unprocessed"
                      }
    while True:
        page = page + 1
        original_param["page"] = page
        response = base_get_request(
            config.BASE_GET_URL,
            params	= original_param,
            headers	= config.BASE_HEADERS,
        )
        piece_items = response['data']
        all_items = all_items + piece_items
        if len(piece_items) == 0:
            break
    return all_items

def get_10_v20Data():
    """
    获得 10 条 v25 的数据
    """
    response = base_get_request(
        config.BASE_GET_URL,
        params	= {"page": 1,
                   "limit": 1000,
                   "os": "ServerE",
                   "os_major_versions[]": "v20",
                   "os_minor_versions[]": "1070",
                   "source__icontains": "kernel-4.19",
                   "vul_upstream_status": "Fixed",
                   "status[]": "unprocessed"
                   },
        headers	= config.BASE_HEADERS,
    )
    items = response['data']
    return items


def get_1_v25Data_withcveid(cveid):
    """
    通过 1 条 cveid 来获得所有架构这条 cveid 对应的 item，方便同源异构的内核一次更新完成所有的状态。
    :param cveid: 字符串 cveid
    """
    response = base_get_request(
        config.BASE_GET_URL,
        headers	= config.BASE_HEADERS,
        params	= {"page": 1,
                   "limit": 10,
                   "os": "Server25",
                   "os_major_versions[]": "v25",
                   "os_minor_versions[]": "2500",
                   "source__icontains": "kernel",
                   "vul_upstream_status": "Fixed",
                   "status[]": "unprocessed",
                   "cveid__icontians": cveid
                   }
    )
    items = response['data']
    return items

@deprecated
def update_1_v25Data_withcveid(vul):
    """
    通过 vul 来更新所有架构的所有 vul 记录状态。
    :param vul: 需要更新的 vul 记录
    """

def update_multiple_items(items):
    """
    更新一系列 items 的状态
    :param cveid: 字符串 cveid
    """
    num = len(items)
    start_time = time.time()
    response = base_post_request(
        config.BASE_UPDATE_URL,
        json	= items,
        headers	= config.BASE_HEADERS,
    )
    elapsed_time = time.time() - start_time
    logger.info("更新： {} 条数据，批状态修改结果: {} ，耗时： {:.4f} 秒".format(
        num, response.get("message"), elapsed_time))
    return response.get("code")
